package com.example.blog.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.lang.Assert;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import java.security.Key;
import java.util.Date;
import java.util.Map;

@Slf4j
public class JWTUtils {
   private static long expiration = 30*60*1000;
   private static String secret = "XX7LWoRwue2WbMUlgopSdpofgAm3K0zIUenGsGD8D0l";
   private static Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));

   //生成令牌
   public static String generateToken(Map<String, Object> claims) {
       return Jwts.builder().
               setClaims(claims).setExpiration(new Date(System.currentTimeMillis() + expiration)).
               signWith(key).compact();
   }

   public static Claims parseToken(String token) {
       log.info("token:{}", token);
       JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
       Claims claims = null;
       try{
           claims = build.parseClaimsJws(token).getBody();
       }catch (Exception e){
           log.error("token校验失败");
       }
       log.info("claims:{}", claims);
       return claims;
   }
   public static Integer getUserId(String token) {
       Claims claims = parseToken(token);
       Assert.notNull(claims,"不存在该用户");
       Integer id = (Integer) claims.get("id");
       return id;
   }

}
